#include "BoundingLine.h"
#include <iostream>
using namespace std;

BoundingLine::BoundingLine(void){
	r = 1.0;
	g = 1.0;
	b = 1.0;
}

BoundingLine::~BoundingLine(void){
}

void BoundingLine::InitLine(Vector3D startPos, Vector3D endPos){
	this->startPos = startPos;
	this->endPos = endPos;
}

void BoundingLine::SetColor(float r, float g, float b){
	this->r = r;
	this->g = g;
	this->b = b;
}

void BoundingLine::DrawLine(void){
	glPushMatrix();
		glColor3f(r, g, b);
		glLineWidth(3);
		glBegin(GL_LINES);
			glVertex2f(startPos.x, startPos.y);
			glVertex2f(endPos.x, endPos.y);
		glEnd();
	glPopMatrix();
}

Vector3D BoundingLine::GetStartPosition(void){
	return startPos;
}

Vector3D BoundingLine::GetEndPosition(void){
	return endPos;
}

bool BoundingLine::HitTest(BoundingBox &box){
	float frontBoxPtX1 = box.GetPosition().x;
	float frontBoxPtX2 = frontBoxPtX1 + box.GetWidth();
	float frontBoxPtY1 = box.GetPosition().y;
	float frontBoxPtY2 = frontBoxPtY1 + box.GetHeight();
	float frontBoxPtZ1 = box.GetPosition().z;
	float frontBoxPtZ2 = frontBoxPtZ1 + box.GetDepth();
	
	if ((this->startPos.x <= frontBoxPtX1 && this->endPos.x <= frontBoxPtX1) || (this->startPos.y <= frontBoxPtY1 && this->endPos.y <= frontBoxPtY1) 
		|| (this->startPos.x >= frontBoxPtX2 && this->endPos.x >= frontBoxPtX2) || (this->startPos.y >= frontBoxPtY2 && this->endPos.y >= frontBoxPtY2))
        return false;

	float m = (this->endPos.y - this->startPos.y) / (this->endPos.x - this->startPos.x);

	float y = m * (frontBoxPtX1 - this->startPos.x) + this->startPos.y;
	if(y > frontBoxPtY1 && y < frontBoxPtY2)
		return true;

	y = m * (frontBoxPtX2 - this->startPos.x) + this->startPos.y;
    if(y > frontBoxPtY1 && y < frontBoxPtY2)
		return true;

	float x = (frontBoxPtY1 - this->startPos.y) / m + this->startPos.x;
    if(x > frontBoxPtX1 && x < frontBoxPtX2) 
		return true;

    x = (frontBoxPtY2 - this->startPos.y) / m + this->startPos.x;
    if(x > frontBoxPtX1 && x < frontBoxPtX2) 
		return true;

	return false;
}